package com.ruoyi.system.service.impl;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.SysFactor;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.domain.DiyStrategy;
import com.ruoyi.system.domain.Factor;
import com.ruoyi.system.mapper.UserFactorItemMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.FactorCategoryMapper;
import com.ruoyi.system.domain.FactorCategory;
import com.ruoyi.system.service.IFactorCategoryService;

/**
 * 因子类别Service业务层处理
 *
 * @author shang
 * @date 2022-01-12
 */
@Service
public class FactorCategoryServiceImpl implements IFactorCategoryService


{
    @Autowired
    private FactorCategoryMapper factorCategoryMapper;
    @Autowired
    private UserFactorItemMapper userFactorItemMapper;

    /**
     * 查询因子类别
     *
     * @param factorCategoryId 因子类别主键
     * @return 因子类别
     */
    @Override
    public FactorCategory selectFactorCategoryByFactorCategoryId(String factorCategoryId)
    {
        return factorCategoryMapper.selectFactorCategoryByFactorCategoryId(factorCategoryId);
    }

    @Override
    public List<Map<String,Object>> getOption() {
        return factorCategoryMapper.getOption();
    }

    @Override
    public List<Map<String, Object>> getFactorList() {
        return factorCategoryMapper.getFactorList();
    }

    /**
     * 查询因子类别列表
     *
     * @param factorCategory 因子类别
     * @return 因子
     */
    @Override
    public List<FactorCategory> selectFactorCategoryList(FactorCategory factorCategory)
    {
        return factorCategoryMapper.selectFactorCategoryList(factorCategory);
    }

    /**
     * 查询因子列表
     *
     * @param factorCategory 因子
     * @return 因子集合
     */
    @Override
    public List<Factor> selectFactorList(FactorCategory factorCategory) {
        if(factorCategory.getFactorCategoryId().equals("9000")){
            SysUser user = SecurityUtils.getLoginUser().getUser();
            if(user.getUserId().toString().equals("1")){
                return factorCategoryMapper.selectUserFactorList(null);
            }else {
                return factorCategoryMapper.selectUserFactorList(user.getUserId().toString());
            }

        }else {
            return factorCategoryMapper.selectFactorList(factorCategory);
        }

    }

    @Override
    public List<SysFactor> findFactorList(FactorCategory factorCategory) {
        return factorCategoryMapper.findFactorList(factorCategory);
    }

    /**
     * 新增因子类别
     *
     * @param factorCategory 因子类别
     * @return 结果
     */
    @Override
    public int insertFactorCategory(FactorCategory factorCategory)
    {
        return factorCategoryMapper.insertFactorCategory(factorCategory);
    }

    /**
     * 修改因子类别
     *
     * @param factorCategory 因子类别
     * @return 结果
     */
    @Override
    public int updateFactorCategory(FactorCategory factorCategory)
    {
        return factorCategoryMapper.updateFactorCategory(factorCategory);
    }

    @Override
    public String insertDiyCategory(DiyStrategy diyStrategy) {
        if(isUseLegal(diyStrategy).equals("数据合法")){
            String strategyContent = diyStrategy.getStrategyContent().replaceAll("&lt;", "<").replaceAll("&gt;", ">")
                    .replaceAll("“","\'").replaceAll("‘","\'").replaceAll("；",";").replaceAll("：",":");
            if(diyStrategy.getStrategyTmpFactor()!=null){
                String strategyTmpFactor=diyStrategy.getStrategyTmpFactor().trim().replaceAll("“","\'").replaceAll("‘","\'").replaceAll("；",";").replaceAll("：",":");
                diyStrategy.setStrategyTmpFactor(strategyTmpFactor);
            }
            diyStrategy.setStrategyCd(IdUtils.fastSimpleUUID());
            SysUser user = SecurityUtils.getLoginUser().getUser();
            diyStrategy.setCreatorId(user.getUserId().toString());
            diyStrategy.setCreatorNm(user.getUserName());
            diyStrategy.setIsInvalid("Y");
            diyStrategy.setCreateTm(DateUtils.getDate());
            diyStrategy.setStrategyContent(strategyContent);
            factorCategoryMapper.insertDiyCategory(diyStrategy);
            return "新增成功";
        }else {
            return isUseLegal(diyStrategy);
        }

    }

    /**
     * 批量删除因子类别
     *
     * @param factorCategoryIds 需要删除的因子类别主键
     * @return 结果
     */
    @Override
    public int deleteFactorCategoryByFactorCategoryIds(String[] factorCategoryIds)
    {
        return factorCategoryMapper.deleteFactorCategoryByFactorCategoryIds(factorCategoryIds);
    }

    /**
     * 删除因子类别信息
     *
     * @param factorCategoryId 因子类别主键
     * @return 结果
     */
    @Override
    public int deleteFactorCategoryByFactorCategoryId(String factorCategoryId)
    {
        return factorCategoryMapper.deleteFactorCategoryByFactorCategoryId(factorCategoryId);
    }

    @Override
    public List<TreeSelect> buildFactorCategoryTreeSelect(List<SysFactor> factors) {
        List<SysFactor> deptTrees = buildDeptTree(factors);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    @Override
    public String verifySom(String data) {
        return isverifySom(data);
    }

    @Override
    public String finduserFactorEng(String data) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        int i = userFactorItemMapper.finduserFactorItemEng(data,user.getUserId().toString());
        if(i>0)
            return "英文名称已经存在！";
        return "验证成功";
    }

    @Override
    public String finduserFactorVerify(String data) {
        List<String> xkh = IdUtils.extractMessageByRegular(data, "(\\=[^\\]]*\\:)");
        if(xkh.isEmpty())
            return "因子非法:没有运算符";
        System.out.println(xkh.get(0));
        if(xkh.get(0).equals(""))
            return "因子非法:没有运算符";
        int count=userFactorItemMapper.findSetOp(xkh.get(0).toUpperCase());
        if(count<=0)
            return "因子非法:运算符不存在";
        String substring = data.substring(data.indexOf(":") + 1);
        if(substring.equals(""))
            return "因子非法:"+ data + "没有条件因子";
        return userOP(substring,",");

    }

    @Override
    public String finduserlongTextUsed(String data) {
        String[] split = data.trim().split(";");
        ArrayList<String> list = new ArrayList<>();
        int i=0;
        for(String s :split){
            i++;
            String trim = s.split("=")[0].replace("/\\d+/g", "").trim();
            if (trim.equals(""))
                return "因子非法:别名不能为纯数字";
            list.add(trim);
            List<String> xkh = IdUtils.extractMessageByRegular(s, "(\\=[^\\]]*\\:)");
            if(xkh.isEmpty())
                return "因子非法:没有运算符";
            System.out.println(xkh.get(0));
            if(xkh.get(0).equals(""))
                return "因子非法:没有运算符";
            int count=userFactorItemMapper.findSetOp(xkh.get(0).toUpperCase());
            if(count<=0)
                return "因子非法:运算符不存在";
            String substring = data.substring(data.indexOf(":") + 1);
            if(substring.equals(""))
                return "因子非法:"+ data + "没有条件因子";
            String[] insplit = substring.split(",");

            for(String ins:insplit){
                int incount = factorCategoryMapper.findFactorByIndexId(ins.split("\\(")[0]);
                if(isNumeric(ins))
                    continue;
                if(i!=1){//如果他不在第一个时；判断它是否是上面定义的别名
                    if(list.contains(ins.split("\\(")[0])){
                        continue;
                    }else {
                        return getvlidins(ins,count);
                    }
                }else {
                    return getvlidins(ins,count);
                }
            }

        }
        return "验证成功";
    }

    private String getvlidins(String zfc,int count){
        if(count==0){
            return  "因子非法:【"+zfc+"】数据库不存在";
        }
        else {
            if (!zfc.contains("("))
                return "因子非法:" + zfc + "没有加入时间范围";
            List<String> inxkh = IdUtils.extractMessageByRegular(zfc, "\\(([^}]*)\\)");
            if (inxkh.get(0).equals("")) {
                return "因子非法:" + zfc + "没有加入时间范围";
            }
        }
        return "验证成功";
    }

    /**
     * 构建前端所需要树结构
     *
     * @param depts 部门列表
     * @return 树结构列表
     */
    public List<SysFactor> buildDeptTree(List<SysFactor> depts)
    {
        List<SysFactor> returnList = new ArrayList<SysFactor>();
        List<Long> tempList = new ArrayList<Long>();
        for (SysFactor dept : depts)
        {
            tempList.add(Long.valueOf(dept.getfactorItemId()));
        }
        for (Iterator<SysFactor> iterator = depts.iterator(); iterator.hasNext();)
        {
            SysFactor dept = (SysFactor) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(Long.valueOf(dept.getParentCategoryId())))
            {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = depts;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysFactor> list, SysFactor t)
    {
        // 得到子节点列表
        List<SysFactor> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysFactor tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysFactor> getChildList(List<SysFactor> list, SysFactor t)
    {
        List<SysFactor> tlist = new ArrayList<SysFactor>();
        Iterator<SysFactor> it = list.iterator();
        while (it.hasNext())
        {
            SysFactor n = (SysFactor) it.next();
            if (StringUtils.isNotNull(n.getParentCategoryId()) && n.getParentCategoryId() .equals(t.getfactorItemId()) )
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysFactor> list, SysFactor t)
    {
        return getChildList(list, t).size() > 0;
    }

    /**
     * 判断是否符合语法标准
     */
    @Override
    public  String isUseLegal(DiyStrategy diyStrategy){

        String s1 = diyStrategy.getStrategyContent();
        String strategyContent = s1.replaceAll("&lt;", "<").replaceAll("&gt;", ">");
        String[] split = strategyContent.split(";");
        for(String sb:split){
            String[] split1 = sb.split(":");
            if(split1.length!=2){
                return "伪代码数据格式非法："+sb;
            }else {
                if(isNumeric(split1[0])){
                    return "伪代码的别名不能为数字【"+split1[0]+"】";
                }else if(split1[0].replaceAll(" ", "").trim().equals("")){
                    return "伪代码的别名不能为空";
                }else if(split1[1].replaceAll(" ", "").trim().equals("")){
                    return "伪代码的条件不能为空";
                }
                else {
                    continue;
                }
            }
        }

        /*String additionalIndex = diyStrategy.getAdditionalIndex();

        if(!StringUtils.isEmpty(additionalIndex)){
            String[] split2 = additionalIndex.split(",");
            for(String ss:split2){
                int incount = factorCategoryMapper.findFactorByIndexId(ss.split("\\(")[0]);
                if(incount==0)
                    return "展示因子【"+ss+"】不存在！";
            }
        }*/

        return "数据合法";
    }


    /**
     * 判断是否为数字，包含负数情况
     * @param str
     * @return
     */
    private boolean isNumeric(String str){
        Boolean flag = false;
        String tmp;
        if(StringUtils.isNotBlank(str)){
            if(str.startsWith("-")){
                tmp = str.substring(1);
            }else{
                tmp = str;
            }
            flag = tmp.matches("^[0.0-9.0]+$");
        }
        return flag;
    }


    /**
     * 判断是否符合语法标准
     */
    private String isverifySom(String data){
        //C1:ROE_5Y(1)>0.05>ROD()
        System.out.println(data);
        String strategyContent1 = data.replaceAll("&lt;", "<").replaceAll("&gt;", ">");
        String strategyContent = strategyContent1.split(":")[1];
        if(strategyContent.contains("<")){
            return userOP(strategyContent,"<");
        }else if(strategyContent.contains(">")){
            return userOP(strategyContent,">");
        }else if(strategyContent.contains("<=")){
            return userOP(strategyContent,"<=");
        }else if(strategyContent.contains(">=")){
            return userOP(strategyContent,">=");
        }else if(strategyContent.contains("=")){
            return userOP(strategyContent,"=");
        }else {
            return "数据不合法【没有比较运算符】";
        }
        }

        private  String userOP(String strategyContent,String ysf){
            String[] split = strategyContent.split(ysf);

            if(split.length<2 && !ysf.equals(","))
                return "没有选择因子或者范围！";
            for(String s:split){
                if(isNumeric(s))
                    continue;
                if(s.contains("\'")||s.contains("\""))
                    continue;
                int count = factorCategoryMapper.findFactorByIndexId(s.split("\\(")[0]);
                if(count==0){
                    continue;
                }
                else {
                    if (!s.contains("("))
                        return "因子非法:" + s + "没有加入时间范围";
                    List<String> xkh = IdUtils.extractMessageByRegular(s, "\\(([^}]*)\\)");
                    if (xkh.get(0).equals("")) {
                        return "因子非法:" + s + "没有加入时间范围";
                    }
                }

//                int count = factorCategoryMapper.findFactorByIndexId(s.split("\\(")[0]);
//                if(count==0)
//                    return "因子非法:【"+s+"】数据库不存在";
            }
            return "验证成功";
        }

        private String userStrategyLogic(String strategyLogic){
            String[] split = strategyLogic.split("\\ *");
            return null;
        }

}
